#include "ftpclient.h"
#include <stdlib.h>

int main(int argc, char *argv[]) {
    if (argc != 3) {
        printf("use %s ip port\n", argv[0]);
        exit(-1);
    }
    int sockfd = init_tcpclient(argv[1], atoi(argv[2]));
    if (-1 == sockfd) {
        exit(-1);
    }
    printf("connect success!\n");
    while (1) {
        fputs("ftp>", stderr);
        char cmd[256] = {0};
        fgets(cmd, sizeof(cmd), stdin);
        /*处理并解析命令*/
        if ((strncmp(cmd, "ls", 2) == 0) || (strncmp(cmd, "LS", 2) == 0)) {
            /*处理用户的ls请求*/
#ifdef DEBUG
            printf("user request ls\n");
#endif
            cmd_ls(sockfd);
            recv_ls_resp(sockfd);
        } else if ((strncmp(cmd, "get", 3) == 0)) {
            /*用户发出了get请求*/
#ifdef DEBUG
            printf("user request get\n");
#endif
            if (strlen(cmd + 4) == 0) {
                fputs("Usage: get filename\n", stderr);
                continue;
            }
            cmd_get(sockfd, cmd + 4);
        } else if ((strncmp(cmd, "put", 3) == 0)) {
            /*用户发出了put请求*/
#ifdef DEBUG
            printf("user request put\n");
#endif
            cmd_put(sockfd, cmd + 4);
        } else if ((strncmp(cmd, "bye", 3) == 0) || (strncmp(cmd, "quit", 4) == 0)) {
            /*用户发出了退出请求*/
#ifdef DEBUG
            printf("user request bye\n");
#endif
            cmd_bye(sockfd);
            printf("Goodbye!\n");
            break;
        } else if (strncmp(cmd, "clear", 5) == 0) {
            system("clear");
        } else if (strncmp(cmd, "pwd", 3) == 0) {
            cmd_pwd(sockfd);
            recv_pwd_resp(sockfd);
        } else if (strncmp(cmd, "cd", 2) == 0) {
            if (strlen(cmd + 3) == 0) {
                fputs("Usage: cd dirname\n", stderr);
                continue;
            }
            cmd_cd(sockfd, cmd + 3);
            recv_cd_resp(sockfd);
        } else if (strncmp(cmd, "_getdir", 7) == 0) {
            if (strlen(cmd + 8) == 0) {
                fputs("Usage: _getdir dirname\n", stderr);
                continue;
            }
            cmd_getdir(sockfd, cmd + 8);
        } else if (strncmp(cmd, "_putdir", 7) == 0) {
            if (strlen(cmd + 8) == 0) {
                fputs("Usage: _putdir dirname\n", stderr);
                continue;
            }
            cmd_putdir(sockfd, cmd + 8);
        } else if (strncmp(cmd, "help", 4) == 0) {
            manual();
        } else if (strncmp(cmd, "stat", 4) == 0) {
            if (strlen(cmd + 5) == 0) {
                fputs("Usage: stat filename", stderr);
                continue;
            }
            cmd_stat(sockfd, cmd + 5);
            recv_stat_resp(sockfd);
        }
    }
    close(sockfd);
}
